package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.GraduateProject;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@Slf4j
@WebServlet("/graduateProject1.ctl")
public class GraduateProjectController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();

        //获取前端请求
        String request_json_str = JSONUtil.getJSON(request);
        try {
            if (!request_json_str.equals("")){
                //从请求数据中读取id对象
                JSONObject id_jsonObject = JSON.parseObject(request_json_str);
                //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
                Object id_obj = id_jsonObject.get("id");
                //如果有请求的id则查询对应id的信息，否则根据查询条件查询所有
                if(id_obj!=null) {
                    //获取id对象的id的值
                    int id_int = Integer.parseInt(id_obj.toString());
                    this.responseGraduateProject(id_int, response);
                } else {
                    //请求中包含条件和分页信息，需要响应多个  对象
                    //读取分页信息，形成分页对象
                    //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                    Pagination pagination = ControllerHelper.getPagination(id_jsonObject);

                    //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
                    List<Condition> conditionList = ControllerHelper.getConditions(id_jsonObject);

                    //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
                    this.responseGraduateProjects(response, conditionList, pagination);
                }
            } else {
                log.info("未收到请求信息！");
                message.put("message","未收到请求信息！");
            }
        } catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.debug(e.getMessage());
            //响应message到前端
            response.getWriter().println(request_json_str);
        }catch(Exception e){
            message.put("message", "网络异常");
            log.debug(e.getMessage(),e);
            //响应message到前端
            response.getWriter().println(request_json_str);
        }
    }

    //响应所有学院对象
    private void responseGraduateProjects(HttpServletResponse response,
                                 List<Condition> conditions_json,
                                 Pagination pagination)
            throws ServletException, IOException, SQLException {
        //分页获得所有学院
        Collection<GraduateProject> graduateProjects
                = GraduateProjectService.getInstance().
                findAll(conditions_json,pagination);
        //第二个参数可以防止循环引用
        String schools_json = JSON.toJSONString(graduateProjects,
                SerializerFeature.DisableCircularReferenceDetect);

        //创建JSON对象message，以便往前端响应totalNum和指定页的元组数据
        JSONObject message = new JSONObject();
        //响应message到前端
        message.put("totalNum",pagination.getTotalNum());
        message.put("data",schools_json);

        response.getWriter().println(message);
    }

    //响应一个学院对象
    private void responseGraduateProject(int id, HttpServletResponse response )
            throws ServletException, IOException, SQLException {
        //根据id查找学院
        GraduateProject graduateProject = GraduateProjectService.getInstance().find(id);
        String school_json = JSON.toJSONString(graduateProject);

        JSONObject resp_jsonObj = new JSONObject();
        resp_jsonObj.put("data", school_json);

        //响应school_json到前端
        response.getWriter().println(school_json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String graduateProject_json = JSONUtil.getJSON(request);
        //将JSON字串解析为School对象
        GraduateProject graduateProjectToAdd =
                JSON.parseObject(graduateProject_json, GraduateProject.class);

        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加School对象
        try {
            GraduateProjectService.getInstance().add(graduateProjectToAdd);
            message.put("message", "增加成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.debug(e.getMessage());
        }catch(Exception e){
            message.put("message", "网络异常");
            log.debug(e.getMessage());
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String graduateProject_json = JSONUtil.getJSON(request);
        //将JSON字串解析为School对象
        GraduateProject graduateProjectToUpdate =
                JSON.parseObject(graduateProject_json, GraduateProject.class);

        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改School对象对应的记录
        try {
            GraduateProjectService.getInstance().update(graduateProjectToUpdate);
            message.put("message", "修改成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.debug(e.getMessage());
        }catch(Exception e){
            message.put("message", "网络异常");
            log.debug(e.getMessage());
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //读取参数id
        String id_str = request.getParameter("id");

        //将请求body解析为要删除的id对应的JSONObject对象(可能是{"id":1})
        JSONObject idOfGraduateProjectToDelete_jsonObj = JSON.parseObject(id_str);
        //从JSONObject对象中读取键“id”的值（Java Object对象），
        Object id_obj = idOfGraduateProjectToDelete_jsonObj.get("id");
        int id_int = Integer.parseInt(id_obj.toString());
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            GraduateProjectService.getInstance().delete(id_int);
            message.put("message", "删除成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.debug(e.getMessage());
        }
        catch(Exception e){
            message.put("message", "网络异常");
            log.debug(e.getMessage());
        }
        //响应message到前端
        response.getWriter().println(message);
    }
}
